//
//  DHMusicPlayerViewController.m
//  Moment
//
//  Created by dllo on 15/12/26.
//  Copyright © 2015年 片刻. All rights reserved.
//

#import "DHMusicPlayerViewController.h"
#import "DHREPlayeRadio.h"
@interface DHMusicPlayerViewController ()<UIScrollViewDelegate>
@property (nonatomic, retain)DHRAdioListView *radioList;
@property (nonatomic, retain)DHPlayerView *playerView;
@property (nonatomic, retain)DHRadioReadView *radioRead;
@property (nonatomic, retain)DHAnchorDescView *anchorDesc;
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)UIView *playView;
@property (nonatomic, retain)UIView *pageOne;
@property (nonatomic, retain)UIView *pageTwo;
@property (nonatomic, retain)UIView *pageThree;
@property (nonatomic, retain)UIView *pageFour;
@property (nonatomic, retain)DHREPlayeRadio *playerRadio;
@property (nonatomic, retain)Moreting *moreting;
@property (nonatomic, retain)NSMutableArray *playListArray;

//三个btn
@property (nonatomic, retain)UIButton *playBtn;
@property (nonatomic, retain)UIButton *lastRadioListBtn;
@property (nonatomic, retain)UIButton *nextRadioListBtn;


@end

@implementation DHMusicPlayerViewController


+(instancetype)shareMusicPlayerViewController{
    static DHMusicPlayerViewController *shareMusicPlayerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareMusicPlayerVC = [[DHMusicPlayerViewController alloc]init];
        
    });
    return shareMusicPlayerVC;
}


- (void)viewDidLoad {
    [super viewDidLoad];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changRadio:) name:@"changRadio" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(listChangRadio:) name:@"changRadioFirst" object:nil];
   [self createViews];
    [self createRadioPlayer];
    UIImage *image = [UIImage imageNamed:@"back.png"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];

    // Do any additional setup after loading the view.
}
-(void)listChangRadio:(NSNotification *)notification{
    if (_mark == 1) {
        DHSubRadio *radio = [[DHSubRadio alloc]init];
        radio = [notification object];
        _tingID = radio.tingid;
    }else{
        _moreting = [notification object];
         _tingID = _moreting.tingid;
    }
    [self getData];
}
-(void)changRadio:(NSNotification *)notification{
    _moreting = [notification object];
    _tingID = _moreting.tingid;
    [self getData1];
    self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
}


-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)timeAction{
    //    设置进度条的最大值为总时长
    self.playerView.mySlider.maximumValue= self.player.duration; //总时长
    self.playerView.mySlider.value = self.player.progress;//当前播放时长
    //    label 显示时间
    NSInteger totalMin = self.player.duration / 60;
    NSInteger totalsec = (NSInteger)self.player.duration % 60;
    
    //
    NSInteger currentMin = self.player.progress / 60;
    NSInteger currentsec = (NSInteger)self.player.progress % 60;
    self.playerView.timeLabel.text = [NSString stringWithFormat:@"%02ld : %02ld/%02ld : %02ld",currentMin,currentsec,totalMin,totalsec];
    if (self.player.state == STKAudioPlayerStateRunning) {
        NSLog(@"播放中");
    }
    
}
-(void)timeAction:(NSTimer *)timer{
    
    self.playerView.mySlider.maximumValue = self.player.duration;//duration 音乐总时长
    self.playerView.mySlider.value = self.player.progress; //当前播放时长
    
    NSInteger zongTime = self.player.duration;
    
    NSInteger min = (NSInteger)(zongTime - self.player.progress)/60;
    NSInteger sec = (NSInteger)(zongTime - self.player.progress)%60;
    //显示时间
    
    self.playerView.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",min,sec];
    if ((NSInteger)self.playerView.mySlider.value + 1 == (NSInteger)self.playerView.mySlider.maximumValue) {
        [self nextRadio:nil];
      }
    
    
    
}
-(void)setHomeData:(TZYHomeData *)homeData{

    if (_homeData != homeData) {
        _homeData = homeData;
    }
    
    _tingID = [_homeData.playInfo objectForKey:@"tingid"];
    NSLog(@"_homeData.playInfo == %@",[_homeData.playInfo objectForKey:@"tingid"]);
    [self getData];

}
-(void)setRadioArr:(NSMutableArray *)radioArr{
    _radioArr = [NSMutableArray array];
    if (_radioArr != radioArr) {
        _radioArr = radioArr;
    }
    _mark = 1;
    [self getData];
    if ([_marker isEqualToString:@"detail"]) {
              _radioList.figure = _figure;
        _radioList.radioListArr = _radioArr;
  
    }
}

-(void)createRadioPlayer{
#pragma mark  播放器对象
    self.player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} } ];
    //定时器
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    
    [self.playerView.mySlider addTarget:self action:@selector(slderAction) forControlEvents:UIControlEventValueChanged];
#pragma mark 传值
    //初始化
}
#pragma mark - 进度条方法
-(void)slderAction{
    
    //改变播放进度
    [self.player seekToTime:self.playerView.mySlider.value];
}
-(void)createViews{

    
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - (SCREEN_HEIGHT * 0.13))];
    [self.view addSubview:_scrollView];
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 4, SCREEN_HEIGHT - 64 - (SCREEN_HEIGHT * 0.13));
    self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = YES;
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    
    _playView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - (SCREEN_HEIGHT * 0.13), SCREEN_WIDTH, SCREEN_HEIGHT * 0.13)];
    [self.view addSubview:_playView];
    _playView.backgroundColor = [UIColor whiteColor];

   
//    播放列表页面
    _radioList = [[DHRAdioListView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _scrollView.frame.size.height)];
    _radioList.radioListArr = [NSMutableArray array];
    _radioList.figure = _figure;
    _radioList.mark = 1;
    _radioList.radioListArr = _radioArr;
    [_scrollView addSubview:_radioList];
    

   
//    播放器页面
    _playerView = [[DHPlayerView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH , 0, SCREEN_WIDTH, _scrollView.frame.size.height)];
    [_scrollView addSubview:_playerView];
    _playerView.backgroundColor = [UIColor whiteColor];

// radioread页面
    _radioRead = [[DHRadioReadView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 2, 0, SCREEN_WIDTH, _scrollView.frame.size.height)];
    
    [_scrollView addSubview:_radioRead];
    
        _radioRead.backgroundColor = [UIColor orangeColor];
//anchorDesc页面
    _anchorDesc = [[DHAnchorDescView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 3, 0, SCREEN_WIDTH, _scrollView.frame.size.height)];
    [_scrollView addSubview:_anchorDesc];
    
    _anchorDesc.radioArr = _radioArr;
    [self createPlayView];
}
//创建playView 上的控件

-(void)createPlayView{
    //    创建playView 的button
    _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _playBtn.frame = CGRectMake((_playView.frame.size.width - (_playView.frame.size.height * 0.35))/2, _playView.frame.size.height * 0.5, _playView.frame.size.height * 0.35, _playView.frame.size.height * 0.35);
        [_playBtn setImage:[UIImage imageNamed:@"iconfont-bofang"]forState:UIControlStateNormal];
    [_playBtn addTarget:self action:@selector(playerAction:) forControlEvents:UIControlEventTouchUpInside];

    [_playView addSubview:_playBtn];
    _playBtn.backgroundColor = [UIColor grayColor];
    
    
    //    上一首按钮
    _lastRadioListBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_lastRadioListBtn setImage:[UIImage imageNamed:@"last1"] forState:UIControlStateNormal];
    [_playView addSubview:_lastRadioListBtn];
    [_lastRadioListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_playBtn.mas_top).offset(_playBtn.frame.size.height * 0.1);
        make.bottom.equalTo(_playBtn.mas_bottom).offset(-_playBtn.frame.size.height * 0.1);
        make.width.equalTo(_lastRadioListBtn.mas_height);
        make.left.equalTo(@(SCREEN_WIDTH * 0.20));
        
    }];
    _lastRadioListBtn.backgroundColor = [UIColor grayColor];
    [_lastRadioListBtn addTarget:self action:@selector(LastRadio:) forControlEvents:UIControlEventTouchUpInside];
    //    下一首按钮
    _nextRadioListBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextRadioListBtn setImage:[UIImage imageNamed:@"next1"] forState:UIControlStateNormal];
    [_playView addSubview:_nextRadioListBtn];
    [_nextRadioListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_playBtn.mas_top).offset(_playBtn.frame.size.height * 0.1);
        make.bottom.equalTo(_playBtn.mas_bottom).offset(-_playBtn.frame.size.height * 0.1);
        make.width.equalTo(_lastRadioListBtn.mas_height);
        make.right.equalTo(@(-SCREEN_WIDTH * 0.20));
    }];
    _nextRadioListBtn.backgroundColor = [UIColor grayColor];
  [_nextRadioListBtn addTarget:self action:@selector(nextRadio:) forControlEvents:UIControlEventTouchUpInside];
    _pageOne = [[UIView alloc]init];
    _pageTwo = [[UIView alloc]init];
    _pageThree = [UIView new];
    _pageFour = [UIView new];
    
    [_playView addSubview:_pageOne];
    [_playView addSubview:_pageTwo];
    [_playView addSubview:_pageThree];
    [_playView addSubview:_pageFour];
    
    [_pageOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_playView.mas_top).offset(_playView.frame.size.height * 0.2);
        make.left.equalTo(@(SCREEN_WIDTH * 0.39));
        make.height.equalTo(@(_playView.frame.size.height * 0.02));
        make.width.equalTo(@(_playView.frame.size.width * 0.03));
        
    }];
    _pageOne.backgroundColor = [UIColor grayColor];
    [_pageTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_pageOne.mas_top);
        make.left.equalTo(_pageOne.mas_right).offset(_playView.frame.size.width * 0.03);
        make.height.equalTo(_pageOne.mas_height);
        make.width.equalTo(_pageOne.mas_width);
        
    }];
_pageTwo.backgroundColor = [UIColor colorWithRed:155 / 255.0 green:198/255.0 blue:121 / 255.0 alpha:1.0];
    [_pageThree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_pageOne.mas_top);
        make.left.equalTo(_pageTwo.mas_right).offset(_playView.frame.size.width * 0.03);
        make.height.equalTo(_pageOne.mas_height);
        make.width.equalTo(_pageOne.mas_width);
        
    }];
    _pageThree.backgroundColor = [UIColor grayColor];
    [_pageFour mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_pageOne.mas_top);
        make.left.equalTo(_pageThree.mas_right).offset(_playView.frame.size.width * 0.03);
        make.height.equalTo(_pageOne.mas_height);
        make.width.equalTo(_pageOne.mas_width);
        
    }];
    _pageFour.backgroundColor = [UIColor grayColor];
    UIView *lineView = [[UIView alloc]init];
    [_playView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(SCREEN_WIDTH * 0.15));
        make.right.equalTo(@(-SCREEN_WIDTH * 0.15));
        make.top.equalTo(_pageOne.mas_bottom).offset(_playView.frame.size.height * 0.1);
        make.height.equalTo(@1);
    }];
    lineView.backgroundColor = [UIColor grayColor];
}
#pragma 播放按钮
-(void)playerAction:(UIButton *)btn{
    if (self.player.state == STKAudioPlayerStatePaused) {
        
 
        [_playBtn setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];//暂停图标
        
         // 通知 抽屉 变为暂停
        [[NSNotificationCenter defaultCenter] postNotificationName:@"stop" object:nil];
        NSLog(@"暂停");
        [self.player resume];//继续
           } else if (self.player.state == STKAudioPlayerStatePlaying) {
        
                [_playBtn setImage:[UIImage imageNamed:@"iconfont-bofang-2.png"] forState:UIControlStateNormal];//播放图标
     
        
        // 通知 抽屉 变为播放
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
        
        
        NSLog(@"播放");
        [self.player pause];//暂停
        
    } else {
        
        [self getData];
        [_playBtn setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];//暂停图标
    }


}
#pragma 上一首
-(void)LastRadio:(UIButton *)btn{

    
    if (self.figure != 0) {
        self.figure = (self.figure - 1);
        NSLog(@"figure == %ld",_figure);
        _radioList.figure = _figure;
        DHSubRadio *radio = _radioArr[_figure];
        _tingID = radio.tingid;
        [self getData];
        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];//暂停图标
        
    } else {
        
        _figure = self.radioArr.count - 1;
         NSLog(@"figure == %ld",_figure);
        _radioList.figure = _figure;
        DHSubRadio *radio = _radioArr[_figure];
        _tingID = radio.tingid;
        [self getData];
       [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
    }
    NSLog(@"上一曲");
}
#pragma mark 下一首
-(void)nextRadio:(UIButton *)btn{
    
    //+1后对总数取余是为了防止点击多次,数组越界
    _figure = (self.figure + 1)%self.radioArr.count;
     NSLog(@"figure *****== %ld",_figure);
    NSLog(@"indexRow = %ld", self.figure);
    //如果歌曲总数大于当前播放的音乐下标
    if (self.figure < self.radioArr.count) {
         NSLog(@"figure == %ld",_figure);
        DHSubRadio *radio = [self.radioArr objectAtIndex:self.figure];
        _radioList.figure = _figure;
        self.tingID = radio.tingid;
        [self getData];
        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
//暂停图标
        
    } else {
         NSLog(@"figure == %ld",_figure);
          _radioList.figure = _figure;
        //如果总数小于当前下标,直接播放取余数后的.也就是从第一首歌开始播放,用户体验是循环播放了
        [self getData];
        [self.playBtn setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];//暂停图标
        
    }
    
    
    NSLog(@"下一曲");
    
}
#pragma mark - 减速停止时触发(滑动结束)
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    
    if (scrollView.contentOffset.x == 0) {
        _pageOne.backgroundColor = [UIColor colorWithRed:155 / 255.0 green:198/255.0 blue:121 / 255.0 alpha:1.0];
        _pageTwo.backgroundColor = [UIColor grayColor];
        _pageThree.backgroundColor = [UIColor grayColor];
        _pageFour.backgroundColor = [UIColor grayColor];
    }else if(scrollView.contentOffset.x == self.view.frame.size.width){
        _pageTwo.backgroundColor = [UIColor colorWithRed:155 / 255.0 green:198/255.0 blue:121 / 255.0 alpha:1.0];
        _pageOne.backgroundColor = [UIColor grayColor];
        _pageThree.backgroundColor = [UIColor grayColor];
        _pageFour.backgroundColor = [UIColor grayColor];
    }else if(scrollView.contentOffset.x == self.view.frame.size.width * 2){
        _pageThree.backgroundColor = [UIColor colorWithRed:155 / 255.0 green:198/255.0 blue:121 / 255.0 alpha:1.0];
        _pageTwo.backgroundColor = [UIColor grayColor];
        _pageOne.backgroundColor = [UIColor grayColor];
        _pageFour.backgroundColor = [UIColor grayColor];
    }else{
        _pageFour.backgroundColor = [UIColor colorWithRed:155 / 255.0 green:198/255.0 blue:121 / 255.0 alpha:1.0];
        _pageTwo.backgroundColor = [UIColor grayColor];
        _pageThree.backgroundColor = [UIColor grayColor];
        _pageOne.backgroundColor = [UIColor grayColor];
    }
}

-(void)getData{
    
    NSString *urlStr = @"http://api2.pianke.me/ting/info";
    NSString *body = [NSString stringWithFormat: @"auth=&client=1&deviceid=9573086A-0F03-4529-818F-432267320CE8&tingid=%@&version=3.0.6",_tingID];
    [GetData postUrl:urlStr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        NSMutableDictionary *data = [result objectForKey:@"data"];
        _playerRadio = [[DHREPlayeRadio alloc]init];
        [_playerRadio setValuesForKeysWithDictionary:data];
        _anchorDesc.PlayerRadio = _playerRadio;
        _playerView.playerRadio = _playerRadio;
        _radioRead.playerRadio = _playerRadio;
        if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"ID"]isEqualToString:_tingID]) {
            [_player playURL:[NSURL URLWithString:_playerRadio.playinfo.musicUrl]];
        
            [[NSUserDefaults standardUserDefaults]setObject:_tingID forKey:@"ID"];
        }
    } failure:^(NSError *error) {
    
    
    }];

}
-(void)getData1{
    
    NSString *urlStr = @"http://api2.pianke.me/ting/info";
    NSString *body = [NSString stringWithFormat: @"auth=&client=1&deviceid=9573086A-0F03-4529-818F-432267320CE8&tingid=%@&version=3.0.6",_tingID];
    [GetData postUrl:urlStr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        NSMutableDictionary *data = [result objectForKey:@"data"];
        _playerRadio = [[DHREPlayeRadio alloc]init];
        [_playerRadio setValuesForKeysWithDictionary:data];
        
        _anchorDesc.PlayerRadio = _playerRadio;
        _playerView.playerRadio = _playerRadio;
        _radioRead.playerRadio = _playerRadio;
        _radioList.figure = _moreting.figure;
        _radioList.mark = 0;
        if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"ID"]isEqualToString:_tingID]) {
          [_player playURL:[NSURL URLWithString:_playerRadio.playinfo.musicUrl]];
            [[NSUserDefaults standardUserDefaults]setObject:_tingID forKey:@"ID"];
        }
        
         } failure:^(NSError *error) {
        
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
